package com.rams.dao.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.rams.connection.manager.MongoConnectionManager;
import com.rams.dao.LoginDao;
import com.rams.domain.vo.User;

@Repository
public class LoginDaoImpl implements LoginDao{

	@Autowired
	MongoConnectionManager mongoConnection;
	
	@Override
	public User getUser(String username) {
		System.out.println("LoginDaoImpl.validateLogin()");
		MongoOperations mongoOperation = mongoConnection.getMongoOperation();
	 
		// query to search user
		Query searchUserQuery = new Query(Criteria.where("username").is(username));
		
		// find the saved user again.
		User savedUser = mongoOperation.findOne(searchUserQuery, User.class);
        return savedUser;
	}

	@Override
	public boolean createNewUser(User user) {
		System.out.println("LoginDaoImpl.createNewUser()");
		MongoOperations mongoOperation = mongoConnection.getMongoOperation();
		try{
//			WriteConcern wc = new WriteConcern("1");
			
			mongoOperation.insert(user);
			return true;
		}catch(MongoException.DuplicateKey e){
			System.out.println("User already present");
			return false;
		}
		
		
	}
	
}
